package com.googlecode.likesql.converter;

import java.util.LinkedList;
import java.util.List;

import com.googlecode.likesql.constant.SqlConstant;
import com.googlecode.likesql.expression.QuestExp;
import com.googlecode.likesql.utils.StringUtils;

/**
 * @author Johny
 *
 */
public class QuestExpConverter implements Converter {

	private final static String QUEST="?";
	
	public String toTemplate(Object obj) {
		QuestExp exp=(QuestExp)obj;
		String pattern=exp.getPattern();
		Object[] values=exp.getValues();
		ConverterTable table=ConverterTable.getInstance();
		Converter cvt=null;
		Object value=null;
		String[] array=new String[values.length];
		
		for(int i=0;i<values.length;i++){
			value=values[i];
			if(value==null || value.equals(QUEST)){
				cvt=table.getDefaultConverter();
			}else{
				cvt=table.getConverter(value.getClass().getName());
			}
			array[i]=cvt.toTemplate(value);
		}
		
		return StringUtils.replaceAll(pattern, SqlConstant.CHAR_FOR_REPLACE, array);
	}

	public String toSql(Object obj) {
		QuestExp exp=(QuestExp)obj;
		String pattern=exp.getPattern();
		Object[] values=exp.getValues();
		ConverterTable table=ConverterTable.getInstance();
		Converter cvt=null;
		Object value=null;
		String[] array=new String[values.length];
		
		for(int i=0;i<values.length;i++){
			value=values[i];
			if(value==null || value.equals(QUEST)){
				cvt=table.getDefaultConverter();
			}else{
				cvt=table.getConverter(value.getClass().getName());
			}
			array[i]=cvt.toSql(value);
		}
		
		return StringUtils.replaceAll(pattern, SqlConstant.CHAR_FOR_REPLACE, array);
	}

	public List toValueList(Object obj) {
		QuestExp exp=(QuestExp)obj;
		Object[] values=exp.getValues();
		List list=new LinkedList();
		for(int i=0;i<values.length;i++){
			list.add(values[i]);
		}
		return list;
	}

}
